<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;

class SaveUserBrowseTotal extends Command
{
    /**
     * The name and signature of the console command.
     * 当前用户当
     * @var string
     */
    protected $signature = 'szsmkj:SaveUserBrowseTotal {userId : 当前用户ID}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计当天总浏览量';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 用户ID
        $userId = $this->argument('userId');

        $sum_browse = User::find($userId)->goods_browse()
            ->whereDate('created_at',now())->where('pagevies','!=','0')
            ->select([
                'user_id','goods_id',
                \DB::raw('SUM(pagevies) as pagevies'),
                \DB::raw('SUM(show_num) as show_num'),
                \DB::raw('SUM(order_num) as order_num'),
                \DB::raw('SUM(deal_num) as deal_num'),
            ])->groupBy('user_id','goods_id')->get();


        foreach ($sum_browse as $item) {
            if ($userBrowseTotal = $item->user->userBrowseTotal()->where('goods_id' , $item->goods_id)->whereDate('created_at',now())->first()){
                $userBrowseTotal->increment('pagevies' , $item->pagevies);
                $userBrowseTotal->increment('order_num' , $item->order_num);
                $userBrowseTotal->increment('deal_num' , $item->deal_num);
                $userBrowseTotal->increment('show_num' , $item->show_num);
            }else{
                $item->user->userBrowseTotal()->create($item->toArray());
                //$item->user->userBrowseTotal()->create([
                    //'user_id'  => $item->user_id,
                    //'goods_id' => $item->goods_id,
                    //'pagevies' => $item->pagevies,
                    //'order_num'=> $item->order_num,
                    //'deal_num' => $item->deal_num,
                    //'show_num' => $item->show_num,
                //]);
            }
        }
    }
}
